import { Tween } from 'cc';
import { _decorator, Component, Node, Label, tween, view, UITransform, Vec3, SpriteAtlas, SpriteFrame, Sprite, Button, ScrollView, find, math, RichText, EventTouch, WebView } from 'cc';
import { App } from '../App';
import CommConst from '../const/CommConst';
import wsTool from '../net/ws';
import { PD } from '../player/PlayerData';
import { loadCommonPreFab, showErrorTip, showRewardBox } from '../tools/PopuUp';
import { TipMg } from '../tools/TipMg';
import UtilTool from '../tools/UtilTool';
import { MineCuePanel } from './minePanel/MineCuePanel';
import ScrollHelper from './ScrollHelper';
const { ccclass, property } = _decorator;

// 商城界面
@ccclass('ShopPanel')
export class ShopPanel extends Component {
    @property(Node)
    contentNode: Node = null;

    @property(Node)
    scrollNode: Node = null;

    @property(Node)
    emptyNode: Node = null;

    @property(SpriteFrame)
    cueFrames = []


    private itemNum = 6
    // [listData]列表数据  [isLoading]是否加载中 [loadOver]是否加载结束(如果没有新的数据则认为是加载结束) [currPage]当前已经请求的第几页的数据 [dataDirty]是否需要重新拉取数据 
    // 记录数据
    private configData = {listData : [], isLoading : false, loadOver : false, currPage : 0, dataDirty : true, pageSize : 30}

    onLoad() {
        UtilTool.setScreen(this.node)

    }

    start() {
        this.node.getComponent(UITransform).setContentSize(view.getVisibleSize())
        UtilTool.setSize(this.scrollNode, 3, [0, 2])
        UtilTool.setSize(this.scrollNode.getChildByName("view"), 3, [0, 2])
        UtilTool.setSize(find("view/content",this.scrollNode), 3, [0, 2])
        UtilTool.setPos(this.scrollNode, [0, 1])

        this.emptyNode.active = true

        let H = UtilTool.getGapSize().height*2
        if (H>0) {
            this.itemNum = this.itemNum + Math.ceil(H/544)
        }

        this.reqListData()

    }

    /**
     * 请求数据
     */
    reqListData(pInit=true) {
        this.configData.isLoading = true
        this.configData.listData = []
        let contentNode = find("view/content",this.scrollNode)
        contentNode.removeAllChildren()

        wsTool.send({msgCode:CommConst.Req_CUE_LIST, "status":0})
        .then((res) => {
            if(res.result == 0) {
                PD.user.currentCue = res.currentUseClub

                this.configData.currPage = this.configData.currPage + 1
                this.configData.isLoading = false
                
                res.clubList.forEach(element => {
                    if (element.status==0){ // 未购买
                        this.configData.listData.push(element)
                    }
                });
                res.clubList.forEach(element => {
                    if (element.status==2){ // 已购买
                        this.configData.listData.push(element)
                    }
                });
                res.clubList.forEach(element => {
                    if (element.status==1){ // 使用中
                        this.configData.listData.push(element)
                    }
                });

                if (res.clubList==null || res.clubList.length < this.configData.pageSize) {
                    this.configData.loadOver = true
                }

                this.emptyNode.active = this.configData.listData.length<=0?true:false

                // 最新请求的数据列表大于0，才会去刷新界面
                if (res.clubList.length>0) {
                    let param = {
                        init:pInit, 
                        data:this.configData.listData, 
                        itemNum:this.itemNum, 
                        itemFun: (obj,idx,objIdx)=>{
                            this.refreshItem(obj,idx,objIdx)
                        },
                        endFun:()=>{
                            this.OnScrollEnd()
                        }
                    }
    
                    this.scrollNode.getComponent(ScrollHelper).setData(param)
                }
            } else {
                showErrorTip(res.result)
            }
        })
    }

    /** 
     * 刷新数据
     * param obj item对象
     * param idx 实际的下标索引
     * param objIdx item本身的下标索引
    */
    // private RichTextformatStr = "<outline color=#3A230A width=4><color=#FFFFFF><size=36>%s</></></>  <outline color=#3A230A width=4><color=#8DD63C><size=36>%s     </></></> <outline color=#3A230A width=4><color=#FFFFFF><size=36>%s</></></>  <outline color=#3A230A width=4><color=#FEBF2D><size=36>%s\n</></></>  <outline color=#3A230A width=4><color=#FFFFFF><size=36>%s</></></>  <outline color=#3A230A width=4><color=#FFFB75><size=36>%s</></></>"
    refreshItem(obj,idx,objIdx) {
        if (this.configData.listData.length <= 0) {
            return
        }

        let data = this.configData.listData[idx]
        let nameLabel = find("bg/nameLabel", obj).getComponent(Label)   // 名字
        let levelLabel = find("bg/levelLabel", obj).getComponent(Label) // 等级
        let cueSprite = find("bg/cueSprite", obj).getComponent(Sprite)  // 球杆图片
        let coinLabel = find("bg/coinLabel", obj)                       // 金币
        let coinSprite = find("bg/coinSprite", obj)                     // 金币图片
        
        let vigorLabel_v = find("bg/propertyNode/vigorLabel_v", obj).getComponent(Label)                     // 力度
        let sightLabel_v = find("bg/propertyNode/sightLabel_v", obj).getComponent(Label)                     // 瞄准
        let charmLabel_v = find("bg/propertyNode/charmLabel_v", obj).getComponent(Label)                     // 角度

        let btn_buy = find("bg/btn_buy", obj)                          // 购买按钮
        let btn_own = find("bg/btn_own", obj)                          // 已拥有按钮
        let btn_upgrade = find("bg/btn_upgrade", obj)                          // 强化按钮
        let usingNode = find("bg/usingNode", obj)                      // 使用中

        nameLabel.string = App.language.getLanguageLab(176)[data.number + ""]
        cueSprite.spriteFrame = this.cueFrames[data.number]
        coinLabel.getComponent(Label).string = data.gold + ""
        // UtilTool.adaptiveLabel3([coinLabel,coinSprite],-420,10)
        // status状态 0:未购买，1:已购买，2:使用中
        coinLabel.active = data.status==0
        coinSprite.active = data.status==0
        levelLabel.node.active = false

        // 球杆属性
        vigorLabel_v.string = data.vigor + ""
        sightLabel_v.string = data.sightLine + ""
        charmLabel_v.string = data.charm + ""

        // 按钮显示
        btn_buy.active = data.status==0
        btn_own.active = data.status==1 || data.status==2
        btn_upgrade.active = false
        usingNode.active = false

        // 立即购买
        App.onClick.removeButtonClickEvent(btn_buy.getComponent(Button),Node.EventType.TOUCH_END)
        App.onClick.addButtonClickEvent(btn_buy.getComponent(Button), async() =>{
            this.clickBuy(data)
        }, this,null,true,Node.EventType.TOUCH_END,null,500);
    }

    // 滚动视图滑到底部回调
    OnScrollEnd() {
        if (this.configData.isLoading) {
            return
        }
        if (this.configData.loadOver) {
            return
        }

        this.reqListData(false)
    }

    /**
     * 立即购买
     * @param data 球杆数据
     */
    async clickBuy(data) {
        App.Audio.playOneShot("click")
        let node = await loadCommonPreFab("prefabs/hall/shop/buyCue", this.node)
        node.getComponent(MineCuePanel).setData(this, data)
    }


    /** 
     * 关闭
      */
    clickClose() {
        App.Audio.playOneShot("click")
        this.node.destroy();
    }
    
}

